package me.flyray.crm.core.modules.netty.client;

import java.util.HashMap;
import java.util.Map;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import net.sf.json.JSONObject;

public class ClientHandler extends SimpleChannelInboundHandler<Object>{
	
	 	@Override
	    public void channelActive(ChannelHandlerContext ctx) throws Exception {
	    }

	    @Override
	    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
	    }

	    @Override
	    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
	            throws Exception {
	        ctx.close();
	    }

		@Override
		protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
			try {
	        	System.out.println(msg);
//	            ByteBuf buf = (ByteBuf) msg;
//	            byte[] req = new byte[buf.readableBytes()];
//	            buf.readBytes(req);
//	            String body = new String(req, "utf-8");
//	            System.out.println("客户端收到消息-Client :" + msg );
	            JSONObject jsonObject = JSONObject.fromObject(msg);
	            Map<String, String> map = (Map)jsonObject;
	            if("requestLock".equals(map.get("type"))){//请求开锁
	            	//客户端完成线下实际开锁动作后 将锁的状态返回到服务端
	            	 Map<String, String>param=new HashMap<String, String>();
	                 param.put("lockId",map.get("lockId"));
	                 param.put("state", "00");
	                 param.put("res", "客户端确认 已经开锁....");
	                 
	                 Channel channel = ctx.channel();
	                 //发送消息, Buffer类型. write需要flush才发送, 可用writeFlush代替
	                 channel.writeAndFlush(Unpooled.copiedBuffer(JSONObject.fromObject(param).toString().getBytes()));
	            }
	        } catch( Exception e) {
	        	e.printStackTrace();
	        } finally {
	            // 记得释放xxxHandler里面的方法的msg参数: 写(write)数据, msg引用将被自动释放不用手动处理; 但只读数据时,!必须手动释放引用数
	             ReferenceCountUtil.release(msg);
	        }
			
		}
}
